package com.liqi.frame.comm.directive;

import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 绝对路径指令
 * Created by liqi on 2019/9/23 0023.
 */
@Component
public class BaseUrlDirective implements TemplateDirectiveModel {
    @Autowired
    private HttpServletRequest request;

    /**
     *
     * @param environment 环境变量
     * @param map 指令参数（储存你所需要的值，随便是什么Key-Value）（必填）
     * @param templateModels 循环变量（返回值）
     * @param templateDirectiveBody 指令内容
     * @throws TemplateException
     * @throws IOException
     */
    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        TemplateScalarModel urlTemplateScalarModel = (TemplateScalarModel)map.get("url");
        String url = urlTemplateScalarModel.getAsString();
        String contextPath = request.getContextPath();
        if (url.startsWith("/")){
            if(url.startsWith("//")){
                //直接用 //xxx.xxx.xx/webcontext 访问
            }else{
                url = (new StringBuilder()).append(contextPath).append(url).toString();
            }
        } else {
            Integer idx=url.indexOf("://");
            if(url.startsWith("http") && (idx>0 && idx<=6)){
                //http:// 或者https:// 访问
            }else{
                url = (new StringBuilder()).append(contextPath).append("/").append(url).toString();
            }
        }

//        templateModels[0] = new SimpleScalar(url);
//        templateDirectiveBody.render(environment.getOut());
        environment.getOut().write(url);
    }
}
